package org.abc.fund.service.factorService;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.abc.fund.entity.factorEntity.*;
import org.abc.fund.repository.factorRepository.DerivedFactorComponentRepository;
import org.abc.fund.repository.factorRepository.DerivedFactorDataRepository;
import org.abc.fund.repository.factorRepository.DerivedFactorRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 衍生因子管理服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class DerivedFactorService {

    private final DerivedFactorRepository derivedFactorRepository;
    private final DerivedFactorComponentRepository derivedFactorComponentRepository;
    private final FactorAlgorithm factorAlgorithm;
    private final DataSourceIngestionHistoryService dataSourceIngestionHistoryService;
    private  final DerivedFactorDataRepository derivedFactorDataRepository;
    /**
     * 创建衍生因子
     */
    public DerivedFactor createDerivedFactor(String name,String factorCode, String operator, List<String> inputFactors, String parameters,String  calculationPeriod, int lookbackPeriod,boolean enabled, String description) throws JsonProcessingException {
        try {
            if (derivedFactorRepository.existsByFactorCode(factorCode)) {
                throw new IllegalArgumentException("衍生因子代码已存在: " + factorCode);
            }
            
            // 创建衍生因子
            DerivedFactor derivedFactor = new DerivedFactor();
            derivedFactor.setFactorCode(factorCode);
            derivedFactor.setFactorName(name);
            derivedFactor.setDescription(description);
            derivedFactor.setOperator(operator);
            derivedFactor.setFormula(parameters);
            derivedFactor.setEnabled(enabled);
            derivedFactor.setCreateTime(LocalDateTime.now());
            derivedFactor.setUpdateTime(LocalDateTime.now());
            
            // 先保存衍生因子
            DerivedFactor savedDerivedFactor = derivedFactorRepository.save(derivedFactor);
            
            // 解析新的权重配置结构
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(parameters);
            
            // 支持新的多因子配置结构
            List<BigDecimal> weights = new ArrayList<>();
            List<String> operators = new ArrayList<>();
            
            // 尝试从新的结构获取数据
            JsonNode weightsNode = rootNode.get("weights");
            JsonNode operatorsNode = rootNode.get("operators");
            JsonNode factorsNode = rootNode.get("factors");
            
            if (weightsNode != null && weightsNode.isArray()) {
                for (int i = 0; i < weightsNode.size(); i++) {
                    double weight = weightsNode.get(i).asDouble();
                    weights.add(BigDecimal.valueOf(weight));
                }
            }
            
            if (operatorsNode != null && operatorsNode.isArray()) {
                for (int i = 0; i < operatorsNode.size(); i++) {
                    operators.add(operatorsNode.get(i).asText());
                }
            }
            
            // 如果从factors节点获取数据
            if (factorsNode != null && factorsNode.isArray()) {
                for (int i = 0; i < factorsNode.size(); i++) {
                    JsonNode factorNode = factorsNode.get(i);
                    if (factorNode.has("weight")) {
                        double weight = factorNode.get("weight").asDouble();
                        weights.add(BigDecimal.valueOf(weight));
                    }
                    if (factorNode.has("operator")) {
                        operators.add(factorNode.get("operator").asText());
                    }
                }
            }
            
            // 如果没有获取到权重，使用默认权重
            if (weights.isEmpty()) {
                for (int i = 0; i < inputFactors.size(); i++) {
                    weights.add(BigDecimal.valueOf(1.0 / inputFactors.size()));
                }
            }
            
            // 如果没有获取到算子，使用默认算子
            if (operators.isEmpty()) {
                for (int i = 0; i < inputFactors.size(); i++) {
                    operators.add("ADD");
                }
            }
            
            // 创建衍生因子组件
            List<DerivedFactorComponent> derivedFactorComponents = new ArrayList<>();
            for (int i = 0; i < inputFactors.size(); i++) {
                DerivedFactorComponent component = new DerivedFactorComponent();
                component.setDerivedFactor(savedDerivedFactor);
                component.setInputFactor(inputFactors.get(i));
                component.setWeight(i < weights.size() ? weights.get(i) : BigDecimal.valueOf(1.0 / inputFactors.size()));
                component.setOperationType(i < operators.size() ? OperationType.valueOf(operators.get(i)) : OperationType.valueOf(operator));
                component.setSortOrder(i);
                derivedFactorComponents.add(component);
            }
            
            // 保存组件
            if (!derivedFactorComponents.isEmpty()) {
                try {
                    List<DerivedFactorComponent> savedComponents = derivedFactorComponentRepository.saveAll(derivedFactorComponents);
                    log.info("成功保存 {} 个衍生因子组件", savedComponents.size());
                } catch (Exception e) {
                    log.error("保存衍生因子组件失败: {}", e.getMessage(), e);
                    throw new RuntimeException("保存衍生因子组件失败: " + e.getMessage(), e);
                }
            } else {
                log.warn("没有衍生因子组件需要保存");
            }
            
            return savedDerivedFactor;
        } catch (Exception e) {
            log.error("创建衍生因子失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建衍生因子失败: " + e.getMessage(), e);
        }
    }

    /**
     * 更新衍生因子
     */
    public DerivedFactor updateDerivedFactor(String factorCode,DerivedFactorDto dto) throws JsonProcessingException {
        try {
            DerivedFactor existingFactor = derivedFactorRepository.findByFactorCode(factorCode)
                    .orElseThrow(() -> new IllegalArgumentException("衍生因子不存在: " + factorCode));
            
            // 检查因子代码是否被其他因子使用
            if (!existingFactor.getFactorCode().equals(dto.getFactorCode()) &&
                    derivedFactorRepository.existsByFactorCode(dto.getFactorCode())) {
                throw new IllegalArgumentException("衍生因子代码已存在: " + dto.getFactorCode());
            }
            
            // 更新衍生因子基本信息
            existingFactor.setFactorCode(dto.getFactorCode());
            existingFactor.setFactorName(dto.getName());
            existingFactor.setDescription(dto.getDescription());
            existingFactor.setOperator(dto.getOperator());
            existingFactor.setFormula(dto.getParameters());
            existingFactor.setEnabled(dto.isEnabled());
            existingFactor.setUpdateTime(LocalDateTime.now());
            
            // 保存更新的衍生因子
            DerivedFactor updatedDerivedFactor = derivedFactorRepository.save(existingFactor);
            
            // 删除旧的组件
            derivedFactorComponentRepository.deleteByDerivedFactor(existingFactor);
            
            // 解析新的权重配置结构
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(dto.getParameters());
            
            // 支持新的多因子配置结构
            List<BigDecimal> weights = new ArrayList<>();
            List<String> operators = new ArrayList<>();
            
            // 尝试从新的结构获取数据
            JsonNode weightsNode = rootNode.get("weights");
            JsonNode operatorsNode = rootNode.get("operators");
            JsonNode factorsNode = rootNode.get("factors");
            
            if (weightsNode != null && weightsNode.isArray()) {
                for (int i = 0; i < weightsNode.size(); i++) {
                    double weight = weightsNode.get(i).asDouble();
                    weights.add(BigDecimal.valueOf(weight));
                }
            }
            
            if (operatorsNode != null && operatorsNode.isArray()) {
                for (int i = 0; i < operatorsNode.size(); i++) {
                    operators.add(operatorsNode.get(i).asText());
                }
            }
            
            // 如果从factors节点获取数据
            if (factorsNode != null && factorsNode.isArray()) {
                for (int i = 0; i < factorsNode.size(); i++) {
                    JsonNode factorNode = factorsNode.get(i);
                    if (factorNode.has("weight")) {
                        double weight = factorNode.get("weight").asDouble();
                        weights.add(BigDecimal.valueOf(weight));
                    }
                    if (factorNode.has("operator")) {
                        operators.add(factorNode.get("operator").asText());
                    }
                }
            }
            
            // 如果没有获取到权重，使用默认权重
            if (weights.isEmpty()) {
                for (int i = 0; i < dto.getInputFactors().size(); i++) {
                    weights.add(BigDecimal.valueOf(1.0 / dto.getInputFactors().size()));
                }
            }
            
            // 如果没有获取到算子，使用默认算子
            if (operators.isEmpty()) {
                for (int i = 0; i < dto.getInputFactors().size(); i++) {
                    operators.add("ADD");
                }
            }
            
            // 创建新的衍生因子组件
            List<DerivedFactorComponent> derivedFactorComponents = new ArrayList<>();
            for (int i = 0; i < dto.getInputFactors().size(); i++) {
                DerivedFactorComponent component = new DerivedFactorComponent();
                component.setDerivedFactor(updatedDerivedFactor);
                component.setInputFactor(dto.getInputFactors().get(i));
                component.setWeight(i < weights.size() ? weights.get(i) : BigDecimal.valueOf(1.0 / dto.getInputFactors().size()));
                component.setOperationType(i < operators.size() ? OperationType.valueOf(operators.get(i)) : OperationType.valueOf(dto.getOperator()));
                component.setSortOrder(i);
                derivedFactorComponents.add(component);
            }
            
            // 保存新组件
            if (!derivedFactorComponents.isEmpty()) {
                try {
                    List<DerivedFactorComponent> savedComponents = derivedFactorComponentRepository.saveAll(derivedFactorComponents);
                    log.info("成功保存 {} 个衍生因子组件", savedComponents.size());
                } catch (Exception e) {
                    log.error("保存衍生因子组件失败: {}", e.getMessage(), e);
                    throw new RuntimeException("保存衍生因子组件失败: " + e.getMessage(), e);
                }
            } else {
                log.warn("没有衍生因子组件需要保存");
            }
            
            return updatedDerivedFactor;
        } catch (Exception e) {
            log.error("更新衍生因子失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新衍生因子失败: " + e.getMessage(), e);
        }
    }

    /**
     * 删除衍生因子
     */
    public void deleteDerivedFactorData(String factorCode) {
        DerivedFactor derivedFactor = derivedFactorRepository.findByFactorCode(factorCode)
                .orElseThrow(() -> new IllegalArgumentException("衍生因子不存在: " + factorCode));

        derivedFactorRepository.deleteByFactorCode(factorCode);
    }
    /**
     * 根据ID查找衍生因子
     */
    @Transactional(readOnly = true)
    public Optional<DerivedFactor> findById(Long id) {
        return derivedFactorRepository.findById(id);
    }
    /**
     * 根据因子代码查找衍生因子
     */
    @Transactional(readOnly = true)
    public Optional<DerivedFactor> findByFactorCode(String factorCode) {
        return derivedFactorRepository.findByFactorCode(factorCode);
    }

    /**
     * 分页查询衍生因子
     */
    @Transactional(readOnly = true)
    public Page<DerivedFactor> findDerivedFactors(Boolean enabled, Pageable pageable) {
        if (enabled == null) {
            return derivedFactorRepository.findAll(pageable);
        }
        return derivedFactorRepository.findByEnabled(enabled, pageable);
    }

    /**
     * 根据是否启用查找衍生因子列表
     */
    @Transactional(readOnly = true)
    public List<DerivedFactor> findByEnabled(Boolean enabled) {
        return derivedFactorRepository.findByEnabled(enabled);
    }

    /**
     * 获取所有衍生因子（支持过滤）
     */
    @Transactional(readOnly = true)
    public List<DerivedFactor> getAllDerivedFactors(Boolean enabled) {
        if (enabled != null) {
            return derivedFactorRepository.findByEnabled(enabled);
        } else {
            return derivedFactorRepository.findAll();
        }
    }
    /**
     * 根据因子名称模糊查询
     */
    @Transactional(readOnly = true)
    public List<DerivedFactor> findByFactorNameContaining(String factorName) {
        return derivedFactorRepository.findByFactorNameContaining(factorName);
    }

    /**
     * 根据因子代码模糊查询
     */
    @Transactional(readOnly = true)
    public List<DerivedFactor> findByFactorCodeContaining(String factorCode) {
        return derivedFactorRepository.findByFactorCodeContaining(factorCode);
    }
    /**
     * 根据创建人查找衍生因子列表
     */
    @Transactional(readOnly = true)
    public List<DerivedFactor> findByCreatedBy(String createdBy) {
        return derivedFactorRepository.findByCreatedBy(createdBy);
    }
    /**
     * 启用/禁用衍生因子
     */
    public DerivedFactor toggleDerivedFactorStatus(Long id, Boolean enabled) {
        DerivedFactor derivedFactor = derivedFactorRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("衍生因子不存在: " + id));
        derivedFactor.setEnabled(enabled);
        derivedFactor.setUpdateTime(LocalDateTime.now());
        return derivedFactorRepository.save(derivedFactor);
    }
    /**
     * 计算衍生因子值
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public BigDecimal calculateDerivedFactorValue(String derivedFactorType, String fundCode) {
        try {
            log.info("开始计算衍生因子: {}, 基金代码: {}", derivedFactorType, fundCode);
            
            // 1. 根据衍生因子类型获取衍生因子配置（包含组件）
            DerivedFactor derivedFactor = derivedFactorRepository.findByFactorCodeWithComponents(derivedFactorType)
                    .orElseThrow(() -> new IllegalArgumentException("未找到该类型的衍生因子配置: " + derivedFactorType));

            if (!derivedFactor.getEnabled()) {
                throw new IllegalArgumentException("衍生因子已禁用: " + derivedFactorType);
            }
            
            // 2. 获取公式组件（按排序顺序）
            List<DerivedFactorComponent> components = derivedFactor.getComponents();
            if (components == null || components.isEmpty()) {
                log.warn("衍生因子 {} 未配置计算公式组件", derivedFactorType);
                throw new IllegalArgumentException("衍生因子未配置计算公式: " + derivedFactorType);
            }
            
            log.info("衍生因子 {} 找到 {} 个计算组件", derivedFactorType, components.size());
            
            // 3. 计算结果
            BigDecimal result = BigDecimal.ZERO;
            boolean hasValidData = false;
            LocalDate today = LocalDate.now();
            LocalDate oneMonthAgo = today.minusMonths(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String todayFormatted = today.format(formatter);
            String oneMonthAgoFormatted = oneMonthAgo.format(formatter);
            
            // 获取基础因子数据
            List<Double> simpleFactor;
            try {
                simpleFactor = dataSourceIngestionHistoryService.getShowData(fundCode, oneMonthAgoFormatted, todayFormatted);
                if (simpleFactor == null || simpleFactor.isEmpty()) {
                    String userMsg = "基金 " + fundCode + " 在 " + oneMonthAgoFormatted + "~" + todayFormatted + " 没有基础因子数据，请先在因子管理中导入相关数据后再计算。";
                    log.warn(userMsg);
                    throw new IllegalArgumentException(userMsg);
                }
            } catch (IllegalArgumentException e) {
                // 只log.warn业务异常
                log.warn(e.getMessage());
                throw e;
            } catch (Exception e) {
                String userMsg = "获取基金 " + fundCode + " 的基础因子数据失败，可能未导入数据或数据格式有误。";
                log.error(userMsg + " 详细: {}", e.getMessage());
                throw new IllegalArgumentException(userMsg);
            }
            
            List<String> missingFactors = new ArrayList<>();
            // 遍历所有组件进行计算
            for (DerivedFactorComponent component : components) {
                // 获取基础因子信息
                String factorName = component.getInputFactor();
                BigDecimal weight = component.getWeight();
                OperationType operationType = component.getOperationType();
                if (factorName == null || factorName.trim().isEmpty()) {
                    log.warn("组件 {} 的输入因子名称为空", component.getId());
                    missingFactors.add("组件" + component.getId() + "(因子名为空)");
                    continue;
                }
                if (weight == null) {
                    log.warn("组件 {} 的权重为空", component.getId());
                    continue;
                }
                if (operationType == null) {
                    log.warn("组件 {} 的操作类型为空", component.getId());
                    continue;
                }
                BigDecimal factorValue = null;
                // 4. 根据基础因子名称获取因子值
                try {
                    switch (factorName) {
                        case "简单收益率因子":
                            factorValue = simpleFactor.size() > 0 ? BigDecimal.valueOf(simpleFactor.get(0)) : null;
                            break;
                        case "年化收益率因子":
                            factorValue = simpleFactor.size() > 1 ? BigDecimal.valueOf(simpleFactor.get(1)) : null;
                            break;
                        case "对数收益率因子":
                            factorValue = simpleFactor.size() > 2 ? BigDecimal.valueOf(simpleFactor.get(2)) : null;
                            break;
                        case "波动率因子":
                            factorValue = simpleFactor.size() > 3 ? BigDecimal.valueOf(simpleFactor.get(3)) : null;
                            break;
                        case "夏普比率因子":
                            factorValue = simpleFactor.size() > 4 ? BigDecimal.valueOf(simpleFactor.get(4)) : null;
                            break;
                        case "最大回撤因子":
                            factorValue = simpleFactor.size() > 5 ? BigDecimal.valueOf(simpleFactor.get(5)) : null;
                            break;
                        case "下行风险因子":
                            factorValue = simpleFactor.size() > 6 ? BigDecimal.valueOf(simpleFactor.get(6)) : null;
                            break;
                        case "相对强弱指数因子":
                            factorValue = simpleFactor.size() > 7 ? BigDecimal.valueOf(simpleFactor.get(7)) : null;
                            break;
                        case "移动平均值因子":
                            factorValue = simpleFactor.size() > 8 ? BigDecimal.valueOf(simpleFactor.get(8)) : null;
                            break;
                        case "申购开放频率因子":
                            factorValue = simpleFactor.size() > 9 ? BigDecimal.valueOf(simpleFactor.get(9)) : null;
                            break;
                        case "赎回开放频率因子":
                            factorValue = simpleFactor.size() > 10 ? BigDecimal.valueOf(simpleFactor.get(10)) : null;
                            break;
                        default:
                            log.warn("未知的基础因子: {}", factorName);
                            missingFactors.add(factorName + "(未知因子)");
                            continue; // 跳过未知因子
                    }
                } catch (IndexOutOfBoundsException e) {
                    log.warn("基础因子数据索引越界: {}, 因子: {}", factorName, fundCode);
                    missingFactors.add(factorName + "(索引越界)");
                    continue;
                }
                if (factorValue == null) {
                    log.warn("基础因子 {} 无有效数据 [基金{}]", factorName, fundCode);
                    missingFactors.add(factorName);
                    continue;
                }
                // 5. 根据算子类型计算
                try {
                    switch (operationType) {
                        case MULTIPLY:
                            if (hasValidData) {
                                result = result.multiply(factorValue).multiply(weight);
                            } else {
                                result = factorValue.multiply(weight);
                                hasValidData = true;
                            }
                            break;
                        case ADD:
                            if (hasValidData) {
                                result = result.add(factorValue.multiply(weight));
                            } else {
                                result = factorValue.multiply(weight);
                                hasValidData = true;
                            }
                            break;
                        case DIVIDE:
                            if (BigDecimal.ZERO.compareTo(factorValue) == 0) {
                                log.warn("除零错误: {} [基金{}]", factorName, fundCode);
                                continue;
                            }
                            if (hasValidData) {
                                result = result.divide(factorValue, 6, RoundingMode.HALF_UP).multiply(weight);
                            } else {
                                result = BigDecimal.ONE.divide(factorValue, 6, RoundingMode.HALF_UP).multiply(weight);
                                hasValidData = true;
                            }
                            break;
                        case SUBTRACT:
                            if (hasValidData) {
                                result = result.subtract(factorValue.multiply(weight));
                            } else {
                                result = factorValue.multiply(weight).negate();
                                hasValidData = true;
                            }
                            break;
                        case WEIGHTED_ADD:
                            if (hasValidData) {
                                result = result.add(factorValue.multiply(weight));
                            } else {
                                result = factorValue.multiply(weight);
                                hasValidData = true;
                            }
                            break;
                        case WEIGHTED_MULTIPLY:
                            if (hasValidData) {
                                result = result.multiply(factorValue).multiply(weight);
                            } else {
                                result = factorValue.multiply(weight);
                                hasValidData = true;
                            }
                            break;
                        default:
                            log.warn("未知的操作类型: {} [基金{}]", operationType, fundCode);
                            continue;
                    }
                } catch (Exception e) {
                    log.error("计算错误: 因子={}, 操作={}, 值={}, 权重={}, 错误={}", 
                             factorName, operationType, factorValue, weight, e.getMessage());
                    continue;
                }
            }
            
            if (!hasValidData) {
                String msg = "没有有效的因子数据进行计算，缺失因子：" + String.join(", ", missingFactors);
                log.warn(msg);
                throw new IllegalArgumentException(msg);
            }
            
            // 6. 保存计算结果
            try {
                saveCalculationResult(derivedFactorType, fundCode, result);
            } catch (Exception e) {
                log.warn("保存计算结果失败: {}", e.getMessage());
                // 不抛出异常，计算结果仍然有效
            }
            
            log.info("衍生因子 {} 计算完成，结果: {}", derivedFactorType, result);
            return result;
            
        } catch (Exception e) {
            log.error("计算衍生因子失败: {} - {}", derivedFactorType, e.getMessage(), e);
            throw new RuntimeException("计算衍生因子失败: " + e.getMessage(), e);
        }
    }

//    /**
//     * 批量计算衍生因子
//     */
//    public void batchCalculateDerivedFactors(List<String> derivedFactorTypes, LocalDate calculationDate) {
//        log.info("开始批量计算衍生因子，数量: {}", derivedFactorTypes.size());
//        int successCount = 0;
//        int failCount = 0;
//        for (String derivedFactorType : derivedFactorTypes) {
//            try {
//                // 获取需要计算的基金列表
//                List<String> fundCodes = getFundCodesForCalculation();
//                for (String fundCode : fundCodes) {
//                    try {
//                        calculateDerivedFactorValue(derivedFactorType, fundCode);
//                        successCount++;
//                    } catch (Exception e) {
//                        log.error("计算衍生因子失败: 因子ID={}, 基金={}, 错误={}", derivedFactorType, fundCode, e.getMessage());
//                        failCount++;
//                    }
//                }
//            } catch (Exception e) {
//                log.error("批量计算衍生因子失败: {}", derivedFactorType, e);
//                failCount++;
//            }
//        }
//
//        log.info("批量计算完成，成功: {}, 失败: {}", successCount, failCount);
//    }

    /**
     * 获取需要计算的基金代码列表
     */
    private List<String> getFundCodesForCalculation() {
        // 这里应该从基金管理模块获取基金列表
        // 暂时返回示例数据
        return List.of("000001", "000002", "000003", "000004", "000005");
    }
    /**
     * 验证衍生因子公式
     */
    public boolean validateFormula(String formula) {
        if (formula == null || formula.trim().isEmpty()) {
            return false;
        }

        // 简单的公式验证逻辑
        // 检查是否包含基本的数学运算符
        String[] operators = {"+", "-", "*", "/", "(", ")"};
        boolean hasOperator = false;

        for (String operator : operators) {
            if (formula.contains(operator)) {
                hasOperator = true;
                break;
            }
        }

        return hasOperator;
    }

    /**
     * 检查因子代码是否存在
     */
    @Transactional(readOnly = true)
    public boolean existsByFactorCode(String factorCode) {
        return derivedFactorRepository.existsByFactorCode(factorCode);
    }
    
    /**
     * 检查衍生因子是否有配置的计算组件
     */
    @Transactional(readOnly = true)
    public boolean hasComponents(String factorCode) {
        try {
            Optional<DerivedFactor> derivedFactor = derivedFactorRepository.findByFactorCodeWithComponents(factorCode);
            return derivedFactor.isPresent() && 
                   derivedFactor.get().getComponents() != null && 
                   !derivedFactor.get().getComponents().isEmpty();
        } catch (Exception e) {
            log.error("检查衍生因子组件失败: {}", e.getMessage());
            return false;
        }
    }


    /**
     * 保存衍生因子计算结果 - 使用独立事务
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveCalculationResult(String derivedFactorType, String fundCode, BigDecimal result) {
        try {
            DerivedFactorData derivedFactorData = new DerivedFactorData();
            derivedFactorData.setValue(Double.valueOf(String.valueOf(result)));
            derivedFactorData.setLastCalculationTime(LocalDateTime.now());
            derivedFactorData.setFundCode(fundCode);
            derivedFactorData.setType(derivedFactorType);
            derivedFactorDataRepository.save(derivedFactorData);
            log.info("成功保存衍生因子计算结果: 因子={}, 基金={}, 值={}", derivedFactorType, fundCode, result);
        } catch (Exception e) {
            log.warn("保存计算结果失败: {}", e.getMessage());
            // 不抛出异常，计算结果仍然有效
        }
    }

    /**
     * 保存衍生因子计算结果
     */
    private void saveDerivedFactorResult(DerivedFactor derivedFactor, BigDecimal result) {
        try {
            DerivedFactorData derivedFactorData = new DerivedFactorData();
           //
        } catch (Exception e) {
            log.error("保存衍生因子计算结果失败: {} - {}", derivedFactor.getId(), e.getMessage());
        }
    }

    /**
     * 多条件搜索衍生因子
     */
    @Transactional(readOnly = true)
    public Page<DerivedFactor> searchDerivedFactors(String name, String code, String operator, 
                                                   Boolean enabled, Pageable pageable) {
        return derivedFactorRepository.searchDerivedFactors(name, code, operator, enabled, pageable);
    }

    public Optional<DerivedFactorData> getLatestCalculationResult(String type, String fundCode) {
        return derivedFactorDataRepository.findTopByTypeAndFundCodeOrderByLastCalculationTimeDesc(type, fundCode);
    }

    public boolean deleteDerivedFactorById(Long id) {
        if (!derivedFactorRepository.existsById(id)) {
            return false;
        }
        derivedFactorRepository.deleteById(id);
        return true;
    }

}